package com.huawei.push.controller.enity;

import com.alibaba.fastjson.JSONObject;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;
import org.springframework.util.StringUtils;

import java.io.Serializable;
import java.security.MessageDigest;

/**
 * 生成token
 */
@Component
public class VivoApplyTokenEnity implements Serializable {
    private static  final Long idl =-1L;
    //token请求地址
    @Value("vivo.tokenUrl")
    private String tokenUrl;

    // vivo的appid
    @Value("${vivo.appId}")
    private String appId;
    //vivo的key
    @Value("${vivo.appKey}")
    private String appKey;
    @Value(("${vivo.secret}"))
    private String secret;

    /**
     * 生成VIVO鉴权token及参数
     * @return
     */

    public String getParamJson(){
        JSONObject jsonObject =new JSONObject();
        if (StringUtils.hasLength(appKey)&&StringUtils.hasLength(appId)&&StringUtils.hasLength(secret)){
            long timeStamp =System.currentTimeMillis();
            jsonObject.put("appId",appId);
            jsonObject.put("appKey",appKey);
            jsonObject.put("timestamp",timeStamp);
            jsonObject.put("sign",AngelinaMD5(appId+appKey+timeStamp+secret));
            return  jsonObject.toJSONString();
        }

        return null;

    }

    //MD5算法生成32位小写
    public String AngelinaMD5(String str) {
        try {
            MessageDigest md = MessageDigest.getInstance("MD5");
            md.update(str.getBytes());
            byte[] b = md.digest();
            int i=0;
            StringBuffer buf = new StringBuffer();
            for (int offset = 0; offset < b.length; offset++) {
                i = b[offset];
                if (i < 0){  i += 256;}
                if (i < 16){ buf.append("0");}
                buf.append(Integer.toHexString(i));
            }
            str = buf.toString();
        } catch (Exception e) {
            e.printStackTrace();

        }
        return str;
    }
}
